package com.hubiao.pro.common.config;

import com.hubiao.pro.common.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Description
 *
 * @author hubiao
 * @since 2021-01-30 15:57
 */
@Slf4j
@Configuration
public class RabbitConfig {

    @Value("${spring.rabbitmq.host}")
    private String host;

    @Value("${spring.rabbitmq.port}")
    private int port;

    @Value("${spring.rabbitmq.username}")
    private String username;

    @Value("${spring.rabbitmq.password}")
    private String password;


    /**
     * 获取rabbitMQ连接
     *
     * @return
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory( host, port );
        connectionFactory.setUsername( username );
        connectionFactory.setPassword( password );
        connectionFactory.setVirtualHost( "/ems" );
        connectionFactory.setPublisherConfirms( true );
        return connectionFactory;
    }


    /**
     * 初始化交换机，将发送到监控中心的队列绑定到这个交换机中
     *
     * @return
     */
    @Bean
    public DirectExchange bindingExchangeMonitor() {
        return new DirectExchange( Constants.MONITOR_EXCHANGE_TEST );
    }

    @Bean
    public Queue queueMonitor() {
        return new Queue( Constants.MONITOR_QUEUE_TEST, true );
    }

    @Bean
    public Binding bindingHouse() {
        //将队列加入交换机中再写入路由里
        return BindingBuilder.bind( queueMonitor() ).to( bindingExchangeMonitor() ).with( Constants.MONITOR_ROUTINGKEY_TEST );
    }


}
